#!/usr/bin/env python

# -------
# Imports:
# -------
import os, logging, StringIO
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.api import users
from settings import *
from core.models import *
from datetime import datetime
from hashlib import md5
from pypng import png

# --------------------------------------
class UploadImage(webapp.RequestHandler):
# --------------------------------------
    # ------------
    def post(self):
    # ------------
        # Get the uploaded image & its width/height
        try:
            img = Image(image= db.Blob(self.request.get("img")))
        except TypeError:
            # If no image was uploaded, then just redirect back to the same page
            # TODO: This should point to a more useful error page
            return self.redirect('/')
        
        imgPng = img.load()
        size = imgPng[3]['size']
    
        # Get the user and upload time
        user = users.get_current_user()
        now = datetime.utcnow()
        md5Hash = md5(img.image).hexdigest()

        # See if we've uploaded the image before...
        imgQuery = Image.all()
        imgQuery.filter('md5_hash =', md5Hash)
        queryResults = imgQuery.fetch(1)
        if len(queryResults) > 0:
            key = queryResults[0].key()
        else:
            # Store the image in the datastore
            img.md5_hash = md5Hash
            img.image_width = size[0]
            img.image_height = size[1]
            img.image_format = 'png'
            img.owner = user
            img.uploaded = now
            img.put()
            key = img.key()

        # Redirect the user to the appropriate page
        self.redirect('/%s' % key.id())
